'''
Descripttion: 
version: 
Author: Born
Date: 2020-02-16 14:03:51
LastEditors: Born
'''
from __future__ import absolute_import, unicode_literals
from celery import shared_task
from django.conf import settings
import subprocess
from django.core.mail import send_mail
from django.core.mail import EmailMessage
from email.mime.base import MIMEBase


@shared_task
def add(x, y):
    return x + y


@shared_task
def mul(x, y):
    return x * y


@shared_task
def xsum(numbers):
    return sum(numbers)


@shared_task
def test(x=15, y=16):
    return x * y


@shared_task
def pan(directory, transformation):
    repository = settings.KETTLE_REPOSITORY_NAME
    username = settings.KETTLE_REPOSITORY_USERNAME
    password = settings.KETTLE_REPOSITORY_PASSWORK
    pan_path = settings.KETTLE_PAN_PATH
    # ktr_path = settings.KETTLE_KTR_PATH.format(category, file)
    # log_path = settings.KETTLE_LOG_PATH.format(category, file, file)
    # log_level = settings.KETTLE_LOG_LEVEL
    command = 'bash {0} -rep={1} -user={2} -pass={3} -dir={4} -trans={5}'.format(pan_path, repository, username,
                                                                                 password, directory, transformation)

    (status, output) = subprocess.getstatusoutput(command)
    text = output.lower()
    for tag in settings.KETTLE_RUN_FINISH_TAGS:
        if -1 == text.find(tag):
            return output

    # 发送告警邮件
    send_mail(
        '数据中心 | 更新失败',
        output,
        'iapp@dgut.edu.cn',
        ['403763307@qq.com'],
        fail_silently=False,
    )
    raise Exception(output)


@shared_task
def access_check_generate_and_send_report(mail):
    from django.core.mail import EmailMessage
    from email.mime.text import MIMEText
    import datetime
    from Dashboard.views import access_check_generate_report

    access_check_generate_report()
    s_date = datetime.datetime.now().strftime('%Y-%m-%d')

    filename = '{}.xlsx'.format(s_date)
    file = open(filename, mode='rb')

    # html = render_to_string('report.html')

    att1 = MIMEText(file.read(), 'base64', 'utf-8')
    att1["Content-Type"] = 'application/octet-stream'
    att1["Content-Disposition"] = 'attachment; filename={}'.format(filename)
    email = EmailMessage(
        subject='数据中心 | 疫情数据分析报表',
        # body=html,
        body='疫情数据分析报表',
        from_email='iapp@dgut.edu.cn',
        to=mail,

    )
    # email.content_subtype = 'html'
    email.attach(att1)
    return '发送成功，请前往邮箱查看' if email.send(fail_silently=False) else '邮件发送失败'
